<?php

namespace App\Http\Controllers\Mp;

use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateHouseRequest;
use App\Http\Resources\HousePaginationCollection;
use App\Http\Service\CountryService;
use App\Http\Service\HouseService;
use App\Jobs\CheckHouse;
use App\Jobs\CheckOrder;
use App\Model\Agent;
use App\Model\Business;
use App\Model\Contract;
use App\Model\ContractTenant;
use App\Model\Country;
use App\Model\House;
use App\Model\Device;
use App\Model\TjCountry;
use App\Model\TtlockData;
use App\Utils\Result;
use App\Utils\Token;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class HouseController extends Controller
{
    protected HouseService $houseService;

    public function __construct(HouseService $houseService)
    {
        $this->houseService = $houseService;
    }

    public function index(Request $request)
    {
        // Get the current page number from the request parameters (default to 1)
        $page = $request->input('page', 1);

        // Get the number of houses to show per page
        $perPage = $request->input('limit',5);
        $keyword = $request->input('keyword');

        $query = House::query();
        $status = $request->input('status');
        $has_device1 = $request->input('has_device1');
        $has_device = $request->input('has_device');
        if ($status == 'hired') {
            $query->whereHas('contract', function ($q) {
                $q->where('status', ContractStatus::YIQIANYUE);
                $q->orWhere('status', ContractStatus::FASTQY);
            });
        }
        if ($status == 'vacant') {
            $query->whereDoesntHave('contract', function ($q) {
                $q->where('status', '<=', ContractStatus::YIQIANYUE);
            });
        }
        if ($status == 'expire') {
            $query->whereHas('contract', function ($q) {
                $q->whereIn('status', [ContractStatus::YIQIANYUE,ContractStatus::FASTQY]);
                $q->where('expired_at', '>', now()->toDateString());
                $q->where('expired_at', '<', now()->addDays(30)->toDateString());
            });
        }
        if ($status == 'fast') {
            $query->whereHas('contract', function ($q) {
                $q->where('status', ContractStatus::FASTQY);
            });
        }

        if ($status == 'expired') {
            $query->whereHas('contract', function ($q) {
                $q->whereIn('status', [ContractStatus::YIQIANYUE,ContractStatus::FASTQY]);
                $q->where('expired_at', '<', now()->toDateString());
            });
        }
        if ($status == 'fail') {
            $query->whereHas('contract', function ($q) {
                $q->whereIn('status', [ContractStatus::YIQIANYUE,ContractStatus::FASTQY]);
                $q->whereHas('bills', function ($q) {
                    $q->where('is_paid', 0)->where('is_close', 0)->where('pay_date', '<', now()->toDateString());
                })->orWhere('expired_at', '<', now()->toDateString());
            });
        }
        if ($status == 'signing') {
            $query->whereHas('contract', function ($q) {
                $q->whereIn('status', [ContractStatus::QIANDINGZHONG, ContractStatus::DAIQIANYUE]);
            });
        }
        if ($request->input('class_id')) {
            $class_id = explode(',',$request->input('class_id'));
            $query->whereIn('house_class_id', $class_id);
        }else{
            $user = $this->getUser();
            if($user->type == 'admin'){
                $query->whereIn('house_class_id',json_decode($user->class_id));
            }else{
                $query->where('business_id', $this->getBusinessId());
            }
        }
        if ($request->input('estate_name')) {
            $query->where('estate_name', $request->input('estate_name'));
        }
        if ($keyword) {
            $query->where(function ($subQuery) use ($keyword) {
                $subQuery->where('estate_name', 'like', "%{$keyword}%")
                    ->orWhere('name', 'like', "%{$keyword}%");
            });
        }
        if ($has_device1 == 'no') {
            $query->whereDoesntHave('device', function ($q) {
                $q->where('type', 1);
            });
        }
//        if ($request->input('sort')) {
//            if ($request->input('sort') == 'created_at:desc') {
//                $query->orderByDesc('created_at');
//            } elseif ($request->input('sort') == 'updated_at:desc') {
//                $query->orderByDesc('updated_at');
//            } else {
//                $query->orderByDesc('created_at');
//            }
//        }
        if($has_device == 1){
            $query->where(function ($q) {
                $q->whereHas('device',function ($q){
                    $q->whereIn('type', [1,2,3,4,5]);
                });
                $q->orWhereHas('lock',function ($q){
                    $q->whereIn('type', [1,3,4]);
                });
            });
        }
        $query->orderBy('estate_name', 'asc')->orderBy('name', 'asc');
        // Get a paginated collection of House models from the database
        $houses = $query->with('contract', 'contract.contractTenant', 'contract.bills', 'device', 'lock')
            ->paginate($perPage, ['*'], 'page', $page);
        return Result::success(new HousePaginationCollection($houses));
    }

    public function getTenant(Request $request)
    {
        $houseId = $request->input('house_id');
        $house = House::query()->where('id', $houseId)
            ->with('contract')->first();
        if ($house->contract) {
            $data['items'] = ContractTenant::query()->where('contract_id', $house->contract->id)->get();
            $data['count'] = ContractTenant::query()->where('contract_id', $house->contract->id)->count();
            $data['should'] = $house->contract->teanet_num;
            return Result::success($data);
        } else {
            return Result::error(401, '该房源当前尚无合同');
        }
    }


    public function getTags(Request $request)
    {
        $tags = House::query()
            ->where('business_id', $this->getBusinessId())
            ->select('tag')
            ->distinct()
            ->get()
            ->pluck('tag')
            ->toArray();
        foreach ($tags as $k => &$tag) {
            if (!$tag) {
                unset($tags[$k]);
            }
        }
        return Result::success($tags);
    }


    public function getFilterConfig()
    {
        $query = House::query();
        $query->where('business_id', $this->getBusinessId());
        $res = $query->groupBy('estate_name')->select(['estate_name'])->get();
        $estateOptions = [];
        foreach ($res as $item) {
            $estateOptions[] = [
                'label' => $item->estate_name,
                'value' => $item->estate_name,
            ];
        }

        $data = [];
        $data[] = [
            'name' => '小区',
            'key' => 'estate_name',
            'options' => $estateOptions
        ];

        $data[] = [
            'name' => '状态',
            'key' => 'status',
            'options' => [
                [
                    'label' => '未出租',
                    'value' => 'vacant',
                ],
                [
                    'label' => '已出租',
                    'value' => 'hired',
                ],
                [
                    'label' => '签订中',
                    'value' => 'signing',
                ],
                [
                    'label' => '房租已逾期',
                    'value' => 'fail',
                ],
                [
                    'label' => '合同快到期',
                    'value' => 'expire',
                ],
                [
                    'label' => '到期未退',
                    'value' => 'expired',
                ]
            ]
        ];
        $data[] = [
            'name' => '排序',
            'key' => 'sort',
            'options' => [
                [
                    'label' => '按创建日期最新',
                    'value' => 'created_at:desc',
                ],
                [
                    'label' => '按操作日期最新',
                    'value' => 'update_at:desc',
                ]
            ]
        ];

        return Result::success($data);
    }

    public function detail($id)
    {
        $house = House::query()->with('contract', 'contract.contractTenant', 'contract.contractRent', 'device')->find($id);
        $status = $this->houseService->getHouseStatusName($house);
        $data = [
            'house' => [
                'id' => $house->id,
                'estate_name' => $house->estate_name,
                'name' => $house->name,
                'status' => $status['status'],
                'status_key' => $status['key'],
                'tenant_name' => $house->tenant_name,
                'master_tenant' => $house->master_tenant,
                'tenant_count' => $house->tenant_count,
                'dianfei' => $house->dianfei,
                'rent' => $house->rent,
                'contract_expired_at' => $house->contract_expired_at,
                'contract' => $house->contract,
                'fang' => $house->fang,
                'ting' => $house->ting,
                'chu' => $house->chu,
                'wei' => $house->wei,
                'deposit_num' => $house->deposit_num,
                'rent_num' => $house->rent_num,
                'rent_num_name' => $house->rent_num_name,
                'size' => $house->size,
                'province' => $house->province,
                'city' => $house->city,
                'district' => $house->district,
            ],
            'device' => $house->device,
            'form' => House::find($id)
        ];
        return Result::success($data);
    }


    public function create(Request $request)
    {
        $data = $request->input('house');
        $user = $this->getUser();
        $query = House::query()->where('business_id', $this->getBusinessId());
            $query->where('province',$data['province']);
            if(isset($data['city'])){
                $query->where('city',$data['city']);
            }
            if(isset($data['district'])){
                $query->where('district',$data['district']);
            }
            if(isset($data['estate_name'])){
                $query->where('estate_name',$data['estate_name']);
            }
            $query ->where('name',$data['name']);
          $house =  $query->first();
        if(!$house){
            $house = new House();
        }
        $house->business_id = $this->getBusinessId();
        if($request->input('classId')){
           $classId = $request->input('classId');
            if(!is_array($classId)){
                $classId = json_decode($classId);
            }
            $house->house_class_id = $classId[0];
        }
        $house->fill($data);
        $deviceData = $request->input('device');
        if ($deviceData && $deviceData['sn']) {
            //$device['business_id'] = $this->getBusinessId();
            //$house->device()->create($device);

            $device = Device::query()->where('sn', $deviceData['sn'])->first();
            if (!$device) {
                return Result::error(400, '设备不存在');
                /*$device['business_id'] = $this->getBusinessId();
                $house->device()->create($device);*/
            } else {
                $house->save();
                if ($deviceData['price'] > 3 && $device->type != 2) {
                    return Result::error(401, '电量单价不可超过3元');
                }
                if($deviceData['price'] > 10 && $device->type == 2){
                    return Result::error(402, '水费单价不可超过10元');
                }

                if (isset($deviceData['basic_price'])) {
                    $device->basic_price = $deviceData['basic_price'];
                }
                if (isset($deviceData['service_price'])) {
                    $device->service_price = $deviceData['service_price'];
                }
                if ($deviceData['price']) {
                    $device->price = $deviceData['price'];
                }
                if ($device->house_id) {
                    return Result::error(1001, '设备已开通，请联系管理员');
                }
                $user = $this->getUser();
                $business = Business::query()->where('user_id', $user->id)->first();
                if ($business->agent_id) {
                    $agents = [19,2,26];
                    if(in_array($business->agent_id, $agents) && in_array($device->agent_id,$agents)){

                    }else{
                        if ($business->agent_id != $device->agent_id && $device->type != 2) {
                            $agent = Agent::query()->where('id', $business->agent_id)
                                ->first();
                            $str = '绑定异常，请联系您的专属客服';
                            if ($agent) {
                                if ($agent->tel_no) {
                                    $str .= ":({$agent->tel_no})";
                                } else {
                                    $str .= ":({$agent->mobile})";
                                }
                            }
                            return Result::error(401, $str);
                        }
                    }
                } else {
                    $business->agent_id = $device->agent_id;
                    $business->save();
                }
                $device->business_amount = $user->month_amount;
                $device->house_id = $house->id;
                $device->bind_at = Carbon::now()->toDateTimeString();
                $device->business_id = $this->getBusinessId();
                $device->save();
            }
        } else {
            $house->save();
        }
        try {
            $country = TjCountry::query()->whereNotNull('name')->get();
            foreach ($country as $v) {
                if ($v->province == $house->province && $v->city == $house->city) {
                    if ($house->district) {
                        if ($v->district == $house->district) {
//                            if ($house->country && $house->country == $v->country) {
//                                $house->country_code = $v->country_code;
//                                $house->save();
//                            } else {
                            if (strpos($house->estate_name, $v->name) !== false) {
                                $house->country_code = $v->country_code;
                                $house->save();
                                break;
                            }
//                            }
                        }
                    } else {
//                        if ($house->country && $house->country == $v->country) {
//                            if($v->name){
//                                if (strpos($house->estate_name, $v->name) !== false) {
//                                    $house->country_code = $v->country_code;
//                                    $house->save();
//                                    break;
//                                }
//                            }else{
//                                $house->country_code = $v->country_code;
//                                $house->save();
//                            }
//                        } else {
                        if (strpos($house->estate_name, $v->name) !== false) {
                            $house->country_code = $v->country_code;
                            $house->save();
                            break;
                        }
//                        }
                    }
                }
            }
            if (!$house->country_code) {
                $country = TjCountry::query()->whereNotNull('country')->get();
                foreach ($country as $v) {
                    if ($v->province == $house->province && $v->city == $house->city) {
                        if ($house->district) {
                            if ($v->district == $house->district) {
                                if ($house->country && $house->country == $v->country) {
                                    $house->country_code = $v->country_code;
                                    $house->save();
                                }
                            }
                        } else {
                            if ($house->country && $house->country == $v->country) {
                                $house->country_code = $v->country_code;
                                $house->save();
                            }
                        }
                    }
                }
            }
            if ($house->country_code) {
                try{
                    $countryPush['name'] = $business->name?$business->name:'未实名';
                    $countryPush['phone'] = $user->mobile;
                    $countryPush['house_id'] = $house->id;
                    $countryPush['address'] = $house->province . $house->city . $house->district . $house->estate_name . $house->name;
                    $countryPush['regionCode'] = $house->country_code;
                    $countryService = new CountryService();
                    $countryService->pushBusiness($countryPush);
                    dispatch(new CheckHouse($business->id))->delay(3);
                    $devicePush['sn'] = $deviceData['sn'];
                    $devicePush['latitude'] = $house->lat;
                    $devicePush['longitude'] = $house->lng;
                    $devicePush['house_id'] = $house->id;
                    $devicePush['regionCode'] = $house->country_code;
                    $countryService->pushDevice($devicePush);
                }catch (\Exception $e){
                    Log::info($e->getMessage());
                }
            }

        } catch (\Exception $e) {
            Log::info($e->getMessage());
        }
        return Result::success($house);
    }

    public function update(Request $request, $id)
    {
        $house = House::query()->where('id', $id)
            ->where('business_id', $this->getBusinessId())
            ->first();
        if (!$house) {
            return Result::error(404, '未找到记录');
        }
        $data = $request->input('house');
        unset($data['rent_num_name'], $data['business_id']);
        $new = $data['province'] . $data['city'] . $data['district'] . $data['estate_name'] . $data['name'];
        $old = $house->province . $house->city . $house->district . $house->estate_name . $house->name;
        $house->fill($data);
        $house->save();
        if ($old != $new) {
            $user = $this->getUser();
            $business = Business::query()->where('user_id', $user->id)->first();
            try {
                $country = TjCountry::query()->get();
                foreach ($country as $v) {
                    if ($v->province == $house->province && $v->city == $house->city) {
                        if ($house->district) {
                            if ($v->district == $house->district) {
                                if ($house->country && $house->country == $v->country) {
                                    if ($v->name) {
                                        if (strpos($house->estate_name, $v->name) !== false) {
                                            $house->country_code = $v->country_code;
                                            $house->save();
                                            break;
                                        }
                                    } else {
                                        $house->country_code = $v->country_code;
                                        $house->save();
                                    }
                                } else {
                                    if (strpos($house->estate_name, $v->name) !== false) {
                                        $house->country_code = $v->country_code;
                                        $house->save();
                                        break;
                                    }
                                }
                            }
                        } else {
                            if ($house->country && $house->country == $v->country) {
                                if ($v->name) {
                                    if (strpos($house->estate_name, $v->name) !== false) {
                                        $house->country_code = $v->country_code;
                                        $house->save();
                                        break;
                                    }
                                } else {
                                    $house->country_code = $v->country_code;
                                    $house->save();
                                }
                            } else {
                                if (strpos($house->estate_name, $v->name) !== false) {
                                    $house->country_code = $v->country_code;
                                    $house->save();
                                    break;
                                }
                            }
                        }
                    }
                }
                if ($business->name && $house->country_code) {
                    $countryPush['name'] = $business->name;
                    $countryPush['phone'] = $user->mobile;
                    $countryPush['house_id'] = $house->id;
                    $countryPush['address'] = $house->province . $house->city . $house->district . $house->estate_name . $house->name;
                    $countryPush['regionCode'] = $house->country_code;
                    $countryService = new CountryService();
                    $countryService->pushBusiness($countryPush);
                    dispatch(new CheckHouse($business->id))->delay(3);
                }
            } catch (\Exception $e) {
                Log::info($e->getMessage());
            }
        }
        $device = $request->input('device');
        if ($device && $device['id']) {
            $deviceModel = $house->device()->where('id', $device['id'])->first();
            if ($deviceModel && $device) {
                $deviceModel->fill($device);
                $deviceModel->bind_at = Carbon::now()->toDateTimeString();
                $deviceModel->save();
            }
        }

        return Result::success();
    }

    public function destroy($id)
    {
        $house = House::query()->where('id', $id)
            ->where('business_id', $this->getBusinessId())
            ->with('contract')
            ->first();
        if (!$house) {
            return Result::error(404, '未找到记录');
        }
        if ($house->contract) {
            return Result::error(401, '已出租的房源无法删除');
        }
        $checkCount = Device::query()->where('house_id', $id)->count();
        $checkLock =TtlockData::query()->where('house_id',$id)->count();
        if ($checkCount || $checkLock) {
            return Result::error(401, '已绑定设备的房源无法删除');
        }

        $house->delete();
        return Result::success();
    }
}
